#include "presentermodel.h"
#include <algorithm>

namespace yc {

PresenterModel::PresenterModel(QObject* parent) : QObject { parent } { }

PresenterModel::~PresenterModel()
{
    qDeleteAll(presenters_);
    presenters_.clear();
}

Presenter* PresenterModel::presenter(int id) const
{
    for (Presenter* p : std::as_const(presenters_)) {
        if (p->id == id) {
            return p;
        }
    }
    return nullptr;
}

void PresenterModel::add(const Presenter& presenter)
{
    if (auto p = this->presenter(presenter.id)) {
        *p = presenter;
        Q_EMIT changed(p, QPrivateSignal());
    } else {
        p = new Presenter { presenter };
        presenters_.push_back(p);
        Q_EMIT added(p, QPrivateSignal());
    }
}

void PresenterModel::remove(int id)
{
    auto it = std::find_if(presenters_.constBegin(), presenters_.constEnd(),
                           [id](Presenter* presenter) { return id == presenter->id; });
    if (it != presenters_.constEnd()) {
        Q_EMIT removed(*it, QPrivateSignal());
        delete *it;
        presenters_.erase(it);
    }
}

void PresenterModel::clear()
{
    if (!presenters_.empty()) {
        Q_EMIT modelAboutToBeReset(QPrivateSignal());
        qDeleteAll(presenters_);
        presenters_.clear();
        Q_EMIT modelReset(QPrivateSignal());
    }
}

Presenter* PresenterModel::find(int platform, const QString& platform_id) const
{
    auto it = std::find_if(presenters_.constBegin(), presenters_.constEnd(),
                           [platform, platform_id](Presenter* presenter) {
                               return platform == presenter->platform
                                       && platform_id == presenter->platform_id;
                           });
    return it != presenters_.constEnd() ? *it : nullptr;
}

void PresenterModel::setPresenterCategory(int id, int category)
{
    if (auto p = presenter(id)) {
        p->category = category;
        Q_EMIT changed(p, QPrivateSignal());
    }
}

void PresenterModel::setPresenterStatus(int id, int status, int active_live, int audience_count,
                                        const QDateTime& update_time, int updater)
{
    if (auto p = presenter(id)) {
        setPresenterStatus(p, status, active_live, audience_count, update_time, updater);
    }
}

void PresenterModel::setPresenterStatus(Presenter* presenter, int status, int active_live,
                                        int audience_count, const QDateTime& update_time,
                                        int updater)
{
    if (presenter) {
        presenter->update_time = update_time;
        presenter->updater = updater;
        if (presenter->status != status || presenter->audience_count != audience_count) {
            presenter->status = status;
            presenter->active_live = active_live;
            presenter->audience_count = audience_count;
            Q_EMIT changed(presenter, QPrivateSignal());
        }
    }
}

} // namespace yc
